<template>
  <!--总体数据-->
  <div>
    <!--总体数据-->
    <SectionContainer class="u-p20 u-pb0">
      <SectionTitle>总体数据
        <el-tooltip
          slot="tip"
          class="item"
          effect="dark"
          placement="top"
          content="数据更新时间2小时，当天数据仅供参考，请以隔天数据为准"
        >
          <i class="iconfont iconfont-10 c-hint-major"></i>
        </el-tooltip>
      </SectionTitle>

      <!-- 筛选 -->
      <el-form
        inline
        class="m-filter"
        label-position="left"
      >
        <el-form-item label="投放时间：">
          <el-date-picker
            :clearable="false"
            v-model="filter.daterange"
            value-format="yyyy-MM-dd"
            size="small"
            type="daterange"
            range-separator="至"
            start-placeholder="投放开始日期"
            end-placeholder="投放结束日期"
            class="u-w300"
            :picker-options="DATERANGE_OPTIONS"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="search"
            size="small"
            type="primary"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </SectionContainer>

    <!--数据报表-->
    <SectionContainer
      class="u-p20"
      v-if="isChartLine"
    >
      <SectionTitle>数据报表</SectionTitle>
      <ChartLine :data="chartOptions"></ChartLine>
    </SectionContainer>

    <!--数据明细-->
    <SectionContainer class="u-p20">
      <SectionTitle>数据明细</SectionTitle>

      <!-- 表格 -->
      <TableFull
        :data="tableData"
        :column-data="tableColumn"
        :total="tableTotal"
        :current-page="page.pageNo"
        @current-change="currentChange"
        @size-change="sizeChange"
      >
        <el-form
          inline
          class="m-filter"
          slot="handle"
        >
          <el-form-item>
            <el-button
              size="small"
              @click="exportReport"
            >导出报表</el-button>
          </el-form-item>
          <el-form-item>
            <CustomTableColumn
              :module="2"
              :columns.sync="tableColumn"
            />
          </el-form-item>
        </el-form>
        <template slot="column">
          <!-- eslint-disable -->
          <el-table-column
            :resizable="false"
            align="center"
            v-for="(item, index) in tableColumn"
            v-if="item.visible"
            :key="index"
            :label="item.label"
            :sort-by="item.prop"
          >
            <el-table-column
              :resizable="false"
              align="center"
              :label="item.prop === 'reportTime' ? '总计' : getTableDataSumValue(item.prop, {rate: ['bidsSuccessRate', 'clickRate', 'realClickRate', 'profitRatio']})"
              :prop="item.prop"
              :width="item.width"
              class-name="u-table--total"
            >
              <template slot-scope="scope">
                <!-- 日期 -->
                <template v-if="item.prop === 'reportTime'">
                  <span v-html="formatMultiLineTime(scope.row[item.prop])"></span>
                </template>
                <!-- 添加百分比号*100 -->
                <template v-else-if="['bidsSuccessRate', 'clickRate', 'realClickRate', 'profitRatio'].indexOf(item.prop) !== -1 && scope.row[item.prop] !== null">{{decimalMultiply(scope.row[item.prop], 100) + '%'}}</template>
                <!-- 其他 -->
                <template v-else>{{scope.row[item.prop]}}</template>
              </template>
            </el-table-column>
          </el-table-column>
        </template>
      </TableFull>
    </SectionContainer>
  </div>
</template>

<script>
import Moment from "moment";

import SectionContainer from "@/components/section-container";
import SectionTitle from "@/components/section-title";
import ChartLine from "@/components/chart-line";
import TableFull from "@/components/table-full";
import CustomTableColumn from "@/components/custom-table-column";

import DATERANGE_OPTIONS from "@/assets/js/daterange-option";
import { sessionStorage, formatMultiLineTime, hasPermission } from "@/utils";
import { decimalMultiply } from "@/utils/decimal";
import permissionMixin from "@/mixins/permission";
import { fetchDataTotal, fetchDataExportTotal } from "@/api";

export default {
  mixins: [permissionMixin],
  components: {
    SectionContainer,
    SectionTitle,
    ChartLine,
    TableFull,
    CustomTableColumn
  },
  data() {
    return {
      DATERANGE_OPTIONS,

      user: sessionStorage.get("USER"),

      planOptions: [],

      filter: {
        // 时间段
        daterange: [
          Moment()
            .subtract(6, "days")
            .format("YYYY-MM-DD"),
          Moment().format("YYYY-MM-DD")
        ]
      },

      page: {
        pageNo: 1,
        pageSize: 50
      },

      // 表格
      tableData: [],
      tableColumn: [
        {
          label: "日期",
          prop: "reportTime",
          fixed: true,
          width: 110,
          visible: true
        },
        {
          label: "实际出价次数",
          prop: "responseNumber",
          visible: hasPermission(["data_user_bidsResponseNumber"])
        },
        {
          label: "实际竞价成功率",
          prop: "bidsSuccessRate",
          visible: hasPermission(["data_user_bidsSuccessRate"])
        },
        {
          label: "曝光数",
          prop: "displayNumber",
          visible: true
        },
        {
          label: "点击数",
          prop: "clickNumber",
          visible: true
        },
        {
          label: "点击率",
          prop: "clickRate",
          visible: true
        },
        {
          label: "点击均价(元)",
          prop: "cpcAveragePrice",
          visible: true
        },
        {
          label: "千次曝光均价(元)",
          prop: "cpmAveragePrice",
          visible: true
        },
        {
          label: "APP开始下载数",
          prop: "downloadStartNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP下载完成数",
          prop: "downloadCompleteNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP开始安装数",
          prop: "installationStartNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP安装完成数",
          prop: "installationCompleteNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP激活数",
          prop: "activationNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP注册数",
          prop: "registeredNumber",
          visible: false,
          custom: true
        },
        {
          label: "总消耗(元)",
          prop: "biddingPrice",
          visible: true
        },
        {
          label: "实际曝光数",
          prop: "realDisplayNumber",
          visible: hasPermission(["data_user_realDisplayNumber"])
        },
        {
          label: "实际点击率",
          prop: "realClickRate",
          visible: hasPermission(["data_user_realClickRate"])
        },
        {
          label: "实际点击均价(元)",
          prop: "realCpcAveragePrice",
          visible: hasPermission(["data_user_realCpcAveragePrice"])
        },
        {
          label: "实际千次曝光均价(元)",
          prop: "realCpmAveragePrice",
          visible: hasPermission(["data_user_realCpmAveragePrice"])
        },
        {
          label: "实际总消耗(元)",
          prop: "realBiddingPrice",
          visible: hasPermission(["data_user_realBiddingPrice"])
        },
        {
          label: "盈利金额(元)",
          prop: "profitAmount",
          visible: hasPermission(["data_user_profitAmount"])
        },
        {
          label: "合计盈利比",
          prop: "profitRatio",
          visible: hasPermission(["data_user_profitRatio"])
        }
      ],
      tableTotal: 0,

      chartOptions: {},
      isChartLine: true
    };
  },
  computed: {
    filterBody() {
      return {
        startTime: this.filter.daterange[0],
        endTime: this.filter.daterange[1]
      };
    }
  },
  methods: {
    decimalMultiply,
    formatMultiLineTime,

    // 导出报表
    exportReport() {
      fetchDataExportTotal({
        query: {
          userId: this.user.userId
        },
        body: this.filterBody
      }).then(res => {
        if (res.data) {
          location.href = res.data;
        }
      });
    },
    // 图表数据
    getChartOptions(data) {
      let ret = {
        legend: {
          left: "70",
          selectedMode: "single"
        },
        xAxis: [],
        series: [
          {
            name: "点击数",
            data: []
          },
          {
            name: "曝光数",
            data: []
          },
          {
            name: "点击率",
            data: []
          },
          {
            name: "点击均价",
            data: []
          },
          {
            name: "千次曝光均价",
            data: []
          },
          {
            name: "总消耗",
            data: []
          }
        ]
      };
      data.forEach(item => {
        ret.xAxis.push(item.reportTime);
        [
          "clickNumber",
          "displayNumber",
          "clickRate",
          "cpcAveragePrice",
          "cpmAveragePrice",
          "biddingPrice"
        ].forEach((serie, index) => {
          ret.series[index].type = "line";
          ret.series[index].lineStyle = {
            width: 3
          };
          ret.series[index].data.push(item[serie]);
        });
      });
      return ret;
    },
    // 查询
    search() {
      this.page.pageNo = 1;
      this.getTable();
    },
    // 获取表格数据
    getTable() {
      this.tableData = [];
      this.tableTotal = 0;
      this.chartOptions = {};
      this.isChartLine = false;
      fetchDataTotal({
        query: {
          userId: this.user.userId
        },
        body: {
          ...this.page,
          ...this.filterBody
        }
      }).then(res => {
        this.isChartLine = !!res.data.echartsList.length;
        this.chartOptions = this.getChartOptions(res.data.echartsList);
        this.tableTotal = res.data.count;
        if (res.data.list && res.data.list.length) {
          this.tableData = this.modTableDataSumList(
            res.data.sumList,
            res.data.list
          );
        }
      });
    },
    // 给第一行数据添加总计相关数据
    modTableDataSumList(sumList, data) {
      let sum = sumList.length ? sumList[0] : {};
      let sumObj = {};
      for (let key in sum) {
        sumObj[`__` + key] = sum[key];
      }
      data[0] = {
        ...data[0],
        ...sumObj
      };
      return data;
    },
    // 获取总计的相关值
    getTableDataSumValue(prop, { rate }) {
      let sum = this.tableData[0] || {};
      let sumProp = `__${prop}`;
      if (sumProp in sum) {
        let value = sum[sumProp];
        // 添加百分比
        if (rate.indexOf(prop) !== -1) {
          return decimalMultiply(value, 100) + "%";
        }
        return String(value);
      }
      return "";
    },
    // 分页
    currentChange(val) {
      this.page.pageNo = val;
      this.getTable();
    },
    sizeChange(val) {
      this.page.pageSize = val;
      this.getTable();
    }
  },
  created() {
    this.getTable();
  }
};
</script>